<?php

class Service_User {

	const UID_KEY = 'uid';
	const GUEST_ID_KEY = 'guest_uid';

	/**
	 * @static
	 * @return bool
	 */
	public static function is_guest() {
		return !(bool) self::current();
	}

	/**
	 * @static
	 * @param Model_User $user
	 * @return void
	 */
	public static function authorize(Model_User $user, $remember = 0) {
		Session::instance()->set(self::UID_KEY, $user->id);
		self::current($user);
		$guest_uid = (string) Session::instance()->get(self::GUEST_ID_KEY);
		if ($guest_uid) {
			Model_Post::reassigne_guest_posts($guest_uid);
		}
		if($remember) {
			self::save_user_authorize_cookie($user);
		}
	}

	public static function process_image($image_data, $filename, Model_User $user = null) {
		if (!$user) {
			$user = Service_User::current();
		}
		$original_w = $image_data[0];
		$original_h = $image_data[1];
		if(!$original_h || !$original_w){
			return;
		}
		
		switch ($image_data[2]) {
			case IMAGETYPE_GIF:
				$original_img = imagecreatefromgif($filename);
				break;
			case IMAGETYPE_JPEG:
				$original_img = imagecreatefromjpeg($filename);
				break;
			case IMAGETYPE_PNG:
				$original_img = imagecreatefrompng($filename);
				break;
		}

		$avatar_w = Kohana::$config->load('image.avatar_w');
		$avatar_h = Kohana::$config->load('image.avatar_h');
		$avatar_image_name = md5(time()) . '.jpg';
		$avatar_filename = $user->get_avatar_path() . $avatar_image_name;
		
		$source_aspect_ratio = $original_w / $original_h;
		$thumbnail_aspect_ratio = $avatar_w / $avatar_h;
		if ($original_w <= $avatar_w && $original_h <= $avatar_h) {
			$thumbnail_image_width = $original_w;
			$thumbnail_image_height = $original_h;
		} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
			$thumbnail_image_width = (int) ($avatar_h * $source_aspect_ratio);
			$thumbnail_image_height = $avatar_h;
		} else {
			$thumbnail_image_width = $avatar_w;
			$thumbnail_image_height = (int) ($avatar_w / $source_aspect_ratio);
		}

		// Calculate coordinator x and y
		if ($thumbnail_image_width > $thumbnail_image_height) {
			$new_x = 0;
			$new_y = ($avatar_h - $thumbnail_image_height) / 2;
		} else {
			$new_x = ($avatar_w - $thumbnail_image_width) / 2;
			$new_y = 0;
		}

		$avatar_img = imagecreatetruecolor($avatar_w, $avatar_h);
		// set background to white
		$white = imagecolorallocate($avatar_img, 255, 255, 255);
		imagefill($avatar_img, 0, 0, $white);

		imagecopyresampled($avatar_img, $original_img, $new_x, $new_y, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $original_w, $original_h);

		imagejpeg($avatar_img, $avatar_filename);
		imagedestroy($avatar_img);
		imagedestroy($original_img);
		return $avatar_image_name;
	}

	/**
	 * 
	 */
	public static function logout() {
		Session::instance()->delete(self::UID_KEY);
		Cookie::delete(self::hash('uid'));
		Cookie::delete(self::hash('upwd'));
	}

	/**
	 * @static
	 * @param Model_User|null $user
	 * @return Model_User|null
	 */
	public static function current(Model_User $user = NULL) {
		static $current;

		if ($user) {
			$current = $user;
		} elseif ($current === NULL) {
			$user_id = Session::instance()->get('uid');

			if ($user_id) {
				$user = Model_User::fetch($user_id);
			}
			$current = $user;
		}


		return $current;
	}

	public static function get_user_unique_id() {
		$guest_uid = (string) Session::instance()->get(self::GUEST_ID_KEY);
		if (!$guest_uid) {
			$guest_uid = (string) new MongoId();
			Session::instance()->set(self::GUEST_ID_KEY, $guest_uid);
		}
		return $guest_uid;
	}

	public static function hash($string) {

		return md5($string . Cookie::$salt);
	}

	public static function get_remind_hash(Model_User $user, $addition_salt = 'remind my solt') {
		return Service_User::hash($user->id . $user->password . $addition_salt);
	}
	
	public static function check_user_logined() {
		if(self::is_guest()) {
			$username = Cookie::get(self::hash('uid'));
			$password = Cookie::get(self::hash('upwd'));
			$username = str_replace(Cookie::$salt, '', base64_decode($username));
			$password = str_replace(Cookie::$salt, '', base64_decode($password));
			
			if($username == '' || $password == '') {
				return false;
			}
			
			$cond = array(
				'email' => $username,
				'password' => $password
			);
			$user = Model_User::get_mapper()->fetch_one($cond);
			
			if($user) {
				self::authorize($user);
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
	
	public static function save_user_authorize_cookie($user) {
		$username = base64_encode(Cookie::$salt . $user->email . Cookie::$salt);
		$password = base64_encode(Cookie::$salt . $user->password . Cookie::$salt);
		
		Cookie::set(self::hash('uid'), $username, 30*24*60*60);
		Cookie::set(self::hash('upwd'), $password, 30*24*60*60);
	}
}